package com.aizuda.boot.modules.third.fastApi;

import com.aizuda.boot.modules.business.contract.dto.UserInfo;
import com.aizuda.boot.modules.business.contract.util.AuthUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.stream.Collectors;

/**
 * @Author sangyirong
 * @ClassName DocumentAgency
 * @Version 1.0
 * @Date 2025/7/23 16:38
 */
@Slf4j
@Tag(name = "FastAPI")
@RestController
@RequestMapping("/documentAgency/**")
public class FastAPIController {


    private static final String BASE_URL = "https://chatweb.aidb.com.cn/";


    @Operation(
            summary = "FastAPI文档代理接口",
            description = "代理接口，用于转发请求到 https://chatweb.aidb.com.cn/docs#/ 的所有接口。\n" +
                    "请求路径格式：/api/documentAgency/{被代理接口的URI}。\n" +
                    "参数格式与被代理的原始接口保持一致。\n" +
                    "支持GET、POST、PUT、DELETE等HTTP方法。")
    @RequestMapping
    public Object documentAgency(HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (null == currentUser || null == currentUser.getId()) {
//            response.setStatus(200);
            return null;
        }

        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();

        // 构建目标URL，包含查询参数
        String targetUrl = BASE_URL + uri.substring("/api/documentAgency/".length());
        if (queryString != null && !queryString.isEmpty()) {
            targetUrl += "?" + queryString;
        }

        try {
            log.info("代理接口请求，method: {}, url: {}", method, targetUrl);
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest.Builder builder = HttpRequest.newBuilder()
                    .uri(URI.create(targetUrl))
                    .timeout(Duration.ofSeconds(60));

            // 赋值请求头
            builder.header("Accept", "*/*");
            builder.header("Accept-Language", "zh-CN,zh;q=0.9,sq;q=0.8");
            builder.header("Authorization", "undefined");
            builder.header("Content-Type", "application/json");
            builder.header("accept", "application/json");
            builder.header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");

            // 设置请求方法和body
            if ("GET".equals(method) || "DELETE".equals(method)) {
                builder.method(method, HttpRequest.BodyPublishers.noBody());
            } else {
                String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
                builder.method(method, HttpRequest.BodyPublishers.ofString(body != null ? body : ""));
            }

            HttpResponse<String> httpResponse = client.send(builder.build(),
                    HttpResponse.BodyHandlers.ofString());

            // 复制响应头
//            httpResponse.headers().map().forEach((name, values) -> {
//                if (!"transfer-encoding".equalsIgnoreCase(name)) {
//                    response.setHeader(name, String.join(",", values));
//                }
//            });

            log.info("代理接口响应，url： {}，statusCode: {}", targetUrl, httpResponse.statusCode());
            return httpResponse.body();
//            response.setStatus(httpResponse.statusCode());
//            response.getWriter().write(httpResponse.body());

        } catch (Exception e) {
            log.error("文档代理异常", e);
//            response.setStatus(500);
            return null;
        }
    }

}
